import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { api } from '../../api';
import './style.scss';

const { Option } = Select;

const UserManagement = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [currentUser, setCurrentUser] = useState(null);
  const [roles, setRoles] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取用户列表
  const fetchUsers = async (params = {}) => {
    setLoading(true);
    try {
      const res = await api.getUserList({
        pageNum: params.current || 1,
        pageSize: params.pageSize || 10,
        ...params
      });
      setUsers(res.records || []);
      setPagination({
        ...pagination,
        total: res.total,
        current: res.current,
        pageSize: res.size
      });
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户角色信息
  const fetchUserRoles = async (userId) => {
    try {
      const res = await api.getUserRoles(userId);
      return res;
    } catch (error) {
      message.error('获取用户角色信息失败');
      return null;
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status, record) => (
        <Select
          value={status}
          style={{ width: 100 }}
          onChange={(value) => handleStatusChange(value, record)}
        >
          <Option value={1}>正常</Option>
          <Option value={0}>禁用</Option>
        </Select>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理添加/编辑用户
  const handleSubmit = async (values) => {
    try {
      if (currentUser) {
        // 更新用户信息
        await api.updateUser({ ...values, id: currentUser.id });
        // 更新用户角色
        await api.setUserRoles(currentUser.id, values.roleIds || []);
        message.success('更新成功');
      } else {
        // 添加新用户
        const res = await api.addUser(values);
        // 设置用户角色
        if (values.roleIds && values.roleIds.length > 0) {
          await api.setUserRoles(res.data.id, values.roleIds);
        }
        message.success('添加成功');
      }
      setVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('操作失败：' + error.message);
    }
  };

  // 处理编辑
  const handleEdit = async (user) => {
    setCurrentUser(user);
    try {
      // 获取用户角色信息
      const roleInfo = await fetchUserRoles(user.id);
      if (roleInfo) {
        form.setFieldsValue({
          ...user,
          roleIds: roleInfo.ownRoles.map(role => role.id)
        });
      }
      setRoles(roleInfo.allRoles || []);
      setVisible(true);
    } catch (error) {
      message.error('获取用户信息失败');
    }
  };

  // 处理状态变更
  const handleStatusChange = async (value, record) => {
    try {
      await api.updateUser({
        id: record.id,
        status: value
      });
      message.success('状态更新成功');
      fetchUsers();
    } catch (error) {
      message.error('状态更新失败：' + error.message);
    }
  };

  // 处理删除
  const handleDelete = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      onOk: async () => {
        try {
          await api.deleteUser([id]);
          message.success('删除成功');
          fetchUsers();
        } catch (error) {
          message.error('删除失败：' + error.message);
        }
      }
    });
  };

  // 处理表格分页
  const handleTableChange = (pagination, filters, sorter) => {
    fetchUsers({
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
      ...sorter
    });
  };

  return (
    <div className="user-management-page">
      <Card>
        <div className="table-operations">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCurrentUser(null);
              form.resetFields();
              setVisible(true);
            }}
          >
            添加用户
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />

        <Modal
          title={currentUser ? '编辑用户' : '添加用户'}
          open={visible}
          onCancel={() => setVisible(false)}
          footer={null}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input disabled={!!currentUser} />
            </Form.Item>
            {!currentUser && (
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password />
              </Form.Item>
            )}
            <Form.Item
              label="昵称"
              name="nickName"
              rules={[{ required: true, message: '请输入昵称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="角色"
              name="roleIds"
              rules={[{ required: true, message: '请选择角色' }]}
            >
              <Select mode="multiple">
                {roles.map(role => (
                  <Option key={role.id} value={role.id}>
                    {role.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button onClick={() => setVisible(false)}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default UserManagement;
